package com.ybw.order.demo.config.wx;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ybwei
 * @Description 支付配置
 * @date 2021/3/22 14:09
 **/
@Configuration
@ConditionalOnClass(WxPayService.class)
@EnableConfigurationProperties(WxMpProperties.class)
public class WxPayConfiguration {
    @Autowired
    private WxMpProperties properties;
    private static Map<String, WxPayService> wxPayServices = new HashMap<>();
    private static Map<String, WxMpProperties.MpConfig> wxPayConfigs = new HashMap<>();
    /**
     *  @Description 默认公众号appid
     *  @author: ybwei
     *  @Date: 2021/3/22 15:17
     */ 
    private String defaultAppid=null;


    @PostConstruct
    public void init() {
        // 代码里 getConfigs()处报错的同学，IDE需要引入lombok插件！
        final List<WxMpProperties.MpConfig> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("添加下相关配置，注意别配错了！");
        }
        //1、赋值wxPayServices
        wxPayServices = configs.stream()
                .map(a -> {
                    WxPayConfig payConfig = new WxPayConfig();
                    payConfig.setAppId(StringUtils.trimToNull(a.getAppId()));
                    payConfig.setMchId(StringUtils.trimToNull(a.getMchId()));
                    payConfig.setMchKey(StringUtils.trimToNull(a.getMchKey()));
                    payConfig.setSubAppId(StringUtils.trimToNull(a.getSubAppId()));
                    payConfig.setSubMchId(StringUtils.trimToNull(a.getSubMchId()));
                    payConfig.setKeyPath(StringUtils.trimToNull(a.getKeyPath()));
                    // 可以指定是否使用沙箱环境
                    payConfig.setUseSandboxEnv(false);

                    WxPayService wxPayService = new WxPayServiceImpl();
                    wxPayService.setConfig(payConfig);
                    return wxPayService;
                }).collect(Collectors.toMap(s -> s.getConfig().getAppId(), a -> a));

        //2、赋值配置
        wxPayConfigs = configs.stream()
                .collect(Collectors.toMap(s -> s.getAppId(), a -> a));

        //3、赋值默认appid
        defaultAppid=configs.stream().map(WxMpProperties.MpConfig::getAppId).findFirst().get();
    }

    /**
     * @Description 根据appid获取WxPayService
     * @Author ybwei
     * @Date 2021/3/22 15:01
     * @Param [appid]
     * @Return com.github.binarywang.wxpay.service.WxPayService
     * @Exception
     */
    public WxPayService getMaService(String appid) {
        //1、如果appid为空，默认首个公众号appid
        if(appid==null){
            appid=defaultAppid;
        }
        //2、路由
        WxPayService wxService = wxPayServices.get(appid);
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        return wxService;
    }

    /**
     * @Description 根据appid获取配置
     * @Author      ybwei
     * @Date        2021/3/22 15:09
     * @Param       [appid]
     * @Return      com.zt.helios.weChat.config.WxMpProperties.MpConfig
     * @Exception   
     */
    public WxMpProperties.MpConfig getMpConfig(String appid) {
        //1、如果appid为空，默认首个公众号appid
        if(appid==null){
            appid=defaultAppid;
        }
        //2、路由
        WxMpProperties.MpConfig mpConfig = wxPayConfigs.get(appid);
        if (mpConfig == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        return mpConfig;
    }

    /**
     * @Description 获取默认appid
     * @Author      ybwei
     * @Date        2021/3/22 19:37
     * @Param       []
     * @Return      java.lang.String
     * @Exception   
     */
    public String getDefaultAppid(){
        return defaultAppid;
    }

}
